#include "qtouchapplication.h"

#include "../lib/corelib/stylehelper.h"
#include "../lib/corelib/manhattanstyle.h"
#include "../include/plugininterface.h"
#include "../include/pageinterface.h"
#include "qresourcemanager.h"


#include "mainwindow.h"
#include "core.h"

#include <QSettings>
#include <QDesktopWidget>
#include <QFile>

#include <QLibrary>

QTouchApplication::QTouchApplication(int argc, char *argv[]):
    QApplication(argc,argv),
    m_core(new core())
{
    setStyle(new ManhattanStyle(QApplication::style()->objectName()));
    StyleHelper::setBaseColor(StyleHelper::DEFAULT_BASE_COLOR);
    m_mainwindow=new MainWindow(m_core);
    initSetting();
     QResourceManager* resource;
     resource=new QResourceManager;
     resource->initResource(QApplication::applicationDirPath()+"/resource");
    ((core*)m_core)->setResourceInterface(resource);
}

QTouchApplication::~QTouchApplication()
{
    saveSetting();
    m_mainwindow->deleteLater();
    delete m_core;
}

void QTouchApplication::initSetting()
{
    QSettings s(this->applicationDirPath()+"/config.ini",QSettings::IniFormat,this);
    QVariant v=s.value("window/geometry");
    if(v.isValid())
    {
        m_mainwindow->restoreGeometry(v.toByteArray());
    }
    else
    {
        QDesktopWidget* dw=desktop();
        m_mainwindow->setGeometry(dw->width()/10,dw->height()/10,dw->width()*4/5,dw->height()*4/5);

        saveSetting();
    }
}

void QTouchApplication::saveSetting()
{
    QFile f(this->applicationDirPath()+"/config.ini");
    if(!f.exists())
    {
        f.open(QIODevice::WriteOnly);
        f.resize(0);
        f.close();
    }

    QSettings s(this->applicationDirPath()+"/config.ini",QSettings::IniFormat,this);
    s.setValue("window/geometry",m_mainwindow->saveGeometry());
}

void QTouchApplication::showPage()
{
    m_mainwindow->projectClose();
    m_mainwindow->showIndex(0);
    m_mainwindow->show();
}


void QTouchApplication::addPlugin(PluginInterface *plugin)
{
    if(plugin!=NULL)
    {
        connect(plugin,SIGNAL(addObject(QObject*)),this,SLOT(addObject(QObject*)));
        plugin->initPlugin(m_core);
        m_pluginList.append(plugin);
    }
}

void QTouchApplication::addObject(QObject *obj)
{
    if(obj->inherits("PageInterface"))
    {
        m_mainwindow->addTabel((PageInterface*)obj);
    }
}
